package com.o2opuzi.lib.email;

import javax.mail.MessagingException;

import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 发送邮件
 * @author Y.hj
 * @date 2016年5月31日
 */
public class MailSender {
	
	private EmailConfig config;
	
	private JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
	
	public MailSender(EmailConfig config) {
		super();
		this.config = config;
	}

	public void send(EmailSendContent content) {
		try {
			javaMailSender.setUsername(config.getUsername());
			javaMailSender.setPassword(config.getPassword());
			javaMailSender.setHost(config.getHost());
			javaMailSender.setDefaultEncoding(config.getEncoding());
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(),true);
			mimeMessageHelper.setSubject(content.getSubject());
			mimeMessageHelper.setTo(content.getTo());
			mimeMessageHelper.setFrom(javaMailSender.getUsername());
			mimeMessageHelper.setText(content.getContent(), true);
			for (Attachment attachment : content.getAttachments()) {
				mimeMessageHelper.addAttachment(attachment.getName(),new AttachmentInputStreamSource(attachment.getData()), attachment.getContextType());
			}
			javaMailSender.send(mimeMessageHelper.getMimeMessage());
		} catch (MailException e) {
			throw new MailSenderException(e);
		} catch (MessagingException e) {
			throw new MailSenderException(e);
		}
	}
}
